package com.woniu.smallmedical.realm;

import com.woniu.smallmedical.entity.Permission;
import com.woniu.smallmedical.entity.User;
import com.woniu.smallmedical.mapper.RolePermissionMapper;
import com.woniu.smallmedical.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @author author
 * @create 2021-09-29-19:24
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RolePermissionMapper rolePermissionMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Object userInfo = principalCollection.getPrimaryPrincipal();
        System.out.println("doGetAuthorizationInfo");

        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        User user = rolePermissionMapper.selectUserPermission((String)userInfo);


        for(Permission permission:user.getRole().getRolePermission())
        {
            simpleAuthorizationInfo.addStringPermission(permission.getPname());
        }

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal =(String)authenticationToken.getPrincipal();
        System.out.println("doGetAuthenticationInfo");
        User user = rolePermissionMapper.selectUserPermission(principal);
        if(!principal.equals(user.getUsername())){
                return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session=subject.getSession();
        session.setAttribute("user", user);
        Object credentials=user.getPassword();
        AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(principal,credentials,this.getName());
        return authenticationInfo;
    }
}
